package cn.gok.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.function.Consumer;

public class HashMap例子 {
    public static void main(String[] args) {
        //常用方法();
        遍历();
    }

    private static void 遍历() {
        Map<Integer, String> map = new HashMap<>();
        System.out.println(map.put(1, "aaa"));
        System.out.println(map.put(2, "bbb"));
        System.out.println(map.put(1, "ccc"));
        for (Integer key : map.keySet()) {
            String value = map.get(key);
            System.out.println(key + "----" + value);
        }
        Iterator<Integer> it = map.keySet().iterator();
        while (it.hasNext()) {
            Integer key = it.next();
            String value = map.get(key);
            System.out.println(key + "----" + value);
        }
        for (Map.Entry<Integer, String> e : map.entrySet()) {
            Integer key = e.getKey();
            String value = e.getValue();
            System.out.println(key + "---" + value);
        }
    }

    private static void 常用方法() {
        Map<Integer, String> map = new HashMap<>();
        //1添加
        System.out.println(map.put(1, "aaa"));
        System.out.println(map.put(2, "bbb"));
        System.out.println(map.put(1, "ccc"));
        System.out.println(map.size());
        System.out.println(map);
        //2删除（指定key删除，返回被删除的键值对的value，不存在则返回null
        System.out.println(map.remove(2));
        System.out.println(map.remove(100));
        System.out.println(map.containsKey(111));
        System.out.println(map.containsValue("ccc"));
        for (Integer key : map.keySet()) {
            String value = map.get(key);
            System.out.println(key + "----" + value);
        }
        Iterator<Integer> it = map.keySet().iterator();
        while (it.hasNext()) {
            Integer key = it.next();
            String value = map.get(key);
            System.out.println(key + "----" + value);
        }
        Consumer<Integer> con = (k) -> {
            System.out.println(k + "***" + map.get(k));
        };
        map.keySet().stream().forEach(con);
        //EntrySet遍历
        for (Map.Entry<Integer, String> e : map.entrySet()) {
            Integer key = e.getKey();
            String value = e.getValue();
            System.out.println(key + "---" + value);
        }
        //改为Integer的遍历方式
        Iterator<Map.Entry<Integer, String>> it2 = map.entrySet().iterator();
        while (it2.hasNext()) {
            Map.Entry<Integer, String> e = it2.next();
            System.out.println(e.getKey() + "---" + e.getValue());
        }
        //流遍历
        Consumer<Map.Entry<Integer, String>> con2 = (e) -> {
            System.out.println(e.getKey() + "---" + e.getValue());//Consumer“消费者”函数式接口-一个入参，没有返回值
        };
        map.entrySet().stream().forEach(con2);
    }
}
